<template>
	<view class="title-bar">
		<view class="member-picker-input input row full-width flex-wrap">
			<view class="tags row" @click="handleOpenPopup">
				<uni-tag 
					class="flex-shrink0 select-member"
					v-for="(selectMember, selectMemberIndex) in selectMemberList" 
					:key="selectMemberIndex" 
					:text="selectMember.nickName"
					:type="tagType(selectMember)" 
					:inverted="false"></uni-tag>
			</view>
			<uni-icons v-show="isShowClearButton" type="clear" size="25" color="#c0c4cc" @click="handleResetClick"></uni-icons>
		</view>
		<uni-popup ref="popup" safeArea background-color="#fff" @maskClick="handleClosePopup">
			<uni-nav-bar v-if="loaded" :title="$t('member.please-select-member')" :border="false" :right-text="$t('ok')" left-icon="left" @clickLeft="handleClosePicker" @clickRight="handlePushMember"></uni-nav-bar>
			<uni-segmented-control 
				v-if="loaded"
				:current="roleIndex" 
				:values="roleNameList" 
				style-type="text"
				active-color="#007aff" 
				@clickItem="handleRoleChange" />
			<scroll-view class="member-list" :scroll-y="true">
				<uni-list>
					<uni-list-item 
						v-for="(member, memberIndex) in memberList" 
						:key="memberIndex" 
						@click="handleMemberClick(member, $event)" 
						clickable>
						<template v-slot:header>
							<view class="row">
								<member-avatar :member="member"></member-avatar>
								<view class="col member-info">
									<text class="cat2bug-text">{{member.nickName}}</text>
									<text class="cat2bug-sub-text">{{$t('phone-number')}}: {{member.phoneNumber}}</text>
									<text class="cat2bug-sub-text">{{$t('email')}}: {{member.email}}</text>
								</view>
							</view>
						</template>
						<template v-slot:footer>
							<view class="slot-box">
							<uni-tag v-if="memberSelectRole(member)" :text="memberSelectRole(member)" :type="tagType(member)" :inverted="false" />
							</view>
						</template>
					</uni-list-item>
				</uni-list>
			</scroll-view>
		</uni-popup>
	</view>
</template>

<script>
	import config from '@/config'
	import {listMemberOfProject, listProjectRole} from "@/api/system/project";
	import MemberAvatar from "@/components/member/member-avatar/index.vue"
	export default {
		name: 'MemberPicker',
		model: {
			type: 'value',
			event: 'input'
		},
		components: { MemberAvatar },
		data() {
			return {
				// 角色页标签索引
				roleIndex: 0,
				// 角色集合
				roleList: [],
				// 选择的成员字典
				selectMemberMap: new Map(),
				// 选择的成员顺序字典
				selectMemberSortMap: new Map(),
				// 成员列表
				memberList: [],
				// 成员查询参数
				queryMember: {
					pageNum: 1,
					pageSize: 10,
					roleId: null,
					params: {
					    search: null
					}
				},
				// 成员总数
				total: 0,
				selectMemberList: []
			}
		},
		props: {
			value: {
				type: Array,
				default: ()=>[],
			},
		},
		watch: {
			value: function(n, o) {
				this.setSelectMemberList(n);
			}
		},
		onReady() {
			this.getRoleList();
			this.getMemberList();
		},
		computed: {
			/** 是否加载完成  */
			loaded() {
				return this.$i18n.locale?true:false;
			},
			/** 是否显示清空按钮  */
			isShowClearButton() {
				return this.selectMemberList.length>0;
			},
			/** 当前项目名称 */
			projectId() {
			    return this.$store.state.user.config.currentProjectId;
			},
			/** 角色名称列表 */
			roleNameList() {
				return [
					...[this.$i18n.t('all')], 
					...this.roleList.map(role=>role.roleNameI18nKey?this.$i18n.t(role.roleNameI18nKey):role.roleName)];
			},
			/** 显示标签的类型 */
			tagType: function () {
				return function (member) {
					return this.selectMemberSortMap.get(member.userId)===1?'primary':'success';
				}
			},
			/** 成员选择的角色 */
			memberSelectRole: function() {
				return function(member) {
					let roleName = null;
					if(this.selectMemberSortMap.has(member.userId))
						roleName = this.selectMemberSortMap.get(member.userId)===1?this.$i18n.t('head'):this.$i18n.t('assistant');
					else 
						roleName = '';
					return roleName;
				}
			}
		},
		methods: {
			/** 重设 */
			reset() {
				this.selectMemberList = [];
				this.selectMemberMap.clear();
				this.selectMemberSortMap.clear();
				this.emit();
			},
			/** 重设 */
			handleResetClick() {
				this.reset();
			},
			/** 关闭弹框 */
			handleClosePicker() {
				this.$refs.popup.close();
				this.handleClosePopup();
			},
			/** 关闭弹框事件 */
			handleClosePopup() {
				this.$emit('close');
			},
			/** 处理打开弹窗事件 */
			handleOpenPopup() {
				this.getMemberList();
				this.$refs.popup.open('bottom');
				this.$emit('open');
			},
			/** 处理角色改变事件 */
			handleRoleChange(e) {
				if (this.roleIndex !== e.currentIndex) {
					this.roleIndex = e.currentIndex;
					if(e.currentIndex===0) {
						// 如果查看全部角色，不设置roleId
						this.queryMember.roleId = null;
					} else {
						const role = this.roleList[e.currentIndex - 1];
						if(role) {
							this.queryMember.roleId = role.roleId;
						}
					}
					this.getMemberList();
				}
			},
			/** 处理成员点击 */
			handleMemberClick(member, event){
				if(this.selectMemberSortMap.has(member.userId)){
					for (let [key, value] of this.selectMemberSortMap) {
						if(value>this.selectMemberSortMap.get(member.userId)) {
							this.selectMemberSortMap.set(key,value-1);
						}
					}
					this.selectMemberSortMap.delete(member.userId, 0);
					this.selectMemberMap.delete(member.userId);
				} else {
					let count = 0;
					for (let [key, value] of this.selectMemberSortMap) {
						if(value>0) {
							count++;
						}
					}
					this.selectMemberSortMap.set(member.userId,count+1);
					this.selectMemberMap.set(member.userId,member);
					this.$set(this.selectMemberMap,member.userId,member);
				}
				this.$forceUpdate();
			},
			/** 设置选择的成员集合 */
			setSelectMemberList(memberIds) {
				this.selectMemberMap.clear();
				this.selectMemberSortMap.clear();
				this.selectMemberMap = new Map();
				this.selectMemberSortMap = new Map();
				if(memberIds) {
					memberIds.forEach((userId, index)=>{
						const member = this.memberList.find(m=>m.userId===userId);
						if(member) {
							this.selectMemberMap.set(member.userId, member);
							this.selectMemberSortMap.set(member.userId, index+1);
						}
					});
				};
				this.selectMemberList = Array.from(this.selectMemberMap.values()).sort((a, b) => this.selectMemberSortMap.get(a.userId) - this.selectMemberSortMap.get(b.userId));
			},
			/** 查询角色集合 */
			getRoleList() {
				listProjectRole(this.projectId).then(res=>{
					this.roleList = res.rows;
				});
			},
			/** 查询成员集合 */
			getMemberList(memberIds) {
				this.queryMember.projectId = this.projectId;
				listMemberOfProject(this.projectId,this.queryMember).then(res=>{
					this.memberList = res.rows;
					this.total = res.total;
					this.setSelectMemberList(this.value);
				});
			},
			/** 向父组件提交选择测成员 */
			handlePushMember() {
				this.selectMemberList = Array.from(this.selectMemberMap.values()).sort((a, b) => this.selectMemberSortMap.get(a.userId) - this.selectMemberSortMap.get(b.userId));
				this.handleClosePicker();
				this.emit();
			},
			/** 更新父组件传递的v-model */
			emit() {
				this.$emit('input', this.selectMemberList.map(u=>u.userId));
			}
		}
	}
</script>

<style lang="scss" scoped>
	::v-deep .member-picker-input {
		.tags {
			flex: 1;
			min-height: 50rpx;
			flex-wrap: wrap;
		}
		.uni-icons {
			flex-shrink: 0;
		}
	}
	.member-list {
		max-height: 60vh;
		overflow-y: auto;
	}
	.select-member {
		display: inline-flex;
		row-gap: 24rpx;
		column-gap: 12rpx;
	}
	.member-info {
		gap: 0;
	}
</style>